package com.jh.paymentchannel.business.impl;

import com.jh.paymentchannel.business.BankCardImgBusiness;
import com.jh.paymentchannel.pojo.BankCardImg;
import com.jh.paymentchannel.repository.BankCardImgRepository;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class BankCardImgBusinessImpl implements BankCardImgBusiness {
    @Autowired
    private BankCardImgRepository bankCardImgRepository;

    @Override
    public HashMap<Object, Object> bankCardImgAuth(String img, long userId) {

        HashMap<Object, Object> map = new HashMap<>();
        String host = "https://bankocr.market.alicloudapi.com";
        String path = "/cardbank";
        String method = "POST";
        String appcode = "efd428002d8f416ea8a6adec212f9b43";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("img", img);

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //获取response的body
            String res = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.fromObject(res);
            String code = jsonObject.getString("code");
            String result = jsonObject.getString("result");
            JSONObject jsonObject1 = JSONObject.fromObject(result);

            if (code != null && "1".equals(code)&&"1".equals(jsonObject1.getString("bank_card_type"))) {
                //识别成功 进行数据保存
                BankCardImg bankCardImg = new BankCardImg();
                bankCardImg.setAuthTime(new Date());
                bankCardImg.setUserId(userId);
                bankCardImg.setCode("1");
                bankCardImg.setMessage(jsonObject.getString("message"));
                bankCardImg.setBankCardNumber(jsonObject1.getString("bank_card_number"));
                bankCardImg.setBankCardType(jsonObject1.getString("bank_card_type"));
                bankCardImg.setBankFullName(jsonObject1.getString("bank_full_name"));
                bankCardImg.setBankName(jsonObject1.getString("bank_name"));
                BankCardImg cardImg = bankCardImgRepository.save(bankCardImg);
                map.put("results", cardImg);
            } else {
                map.put("error", "识别失败或者不是储蓄卡");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
